package cn.lystudio.rohmtimeopwide_background_v11.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.lystudio.rohmtimeopwide_background_v11.entity.dto.AbnormalItemDTO;
import cn.lystudio.rohmtimeopwide_background_v11.entity.dto.MachineDTO;
import cn.lystudio.rohmtimeopwide_background_v11.entity.po.AbHandleItemPO;
import cn.lystudio.rohmtimeopwide_background_v11.entity.po.AbnormalItemPO;
import cn.lystudio.rohmtimeopwide_background_v11.entity.po.DepartmentsPO;
import cn.lystudio.rohmtimeopwide_background_v11.entity.po.MachinePO;
import cn.lystudio.rohmtimeopwide_background_v11.mapper.AbHandleItemPOMapper;
import cn.lystudio.rohmtimeopwide_background_v11.mapper.AbnormalItemPOMapper;
import cn.lystudio.rohmtimeopwide_background_v11.service.AbnormalItemService;
import cn.lystudio.rohmtimeopwide_background_v11.service.MachineService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
@DS("master")

public class AbnormalItemServiceImpl implements AbnormalItemService {
    @Resource
    private AbnormalItemPOMapper abnormalItemPOMapper;
    @Resource
    private AbHandleItemPOMapper abHandleItemPOMapper;
    private MachineService machineService;

    @Lazy
    @Autowired
    public void setMachineService(MachineService machineService) {
        this.machineService = machineService;
    }

    @Override
    public List<AbnormalItemDTO> getAll(String keyword) {
        // 1.获取设备权限(已鉴权)
        List<MachineDTO> machineDTOList = machineService.getAll(null);
        // 1.1 过滤machine.enabled=true数据
        CollUtil.filter(machineDTOList, machineDTO -> {
            return machineDTO.getMachine().getEnabled();
        });
        // 1.2.组装 secDeptIDList和 machineNoList
        Set<Integer> secDeptIDList = new ConcurrentHashSet<>();
        Set<DepartmentsPO> secDeptList = new ConcurrentHashSet<>();
        Set<String> machineNoList = new ConcurrentHashSet<>();
        CollUtil.forEach(machineDTOList.iterator(), (machineDTO, index) -> {
            secDeptIDList.add(machineDTO.getSecDept().getDepartmentID());
            secDeptList.add(machineDTO.getSecDept());
            machineNoList.add(machineDTO.getMachine().getMachineNo());
        });
        if (CollUtil.isEmpty(secDeptIDList) || CollUtil.isEmpty(machineNoList) || CollUtil.isEmpty(secDeptList))
            return null;
        // 2.获取异常项目List
        LambdaQueryWrapper<AbnormalItemPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AbnormalItemPO::getSecDeptID, secDeptIDList)
                .or()
                .in(AbnormalItemPO::getBelong2MacNo, machineNoList);
        List<AbnormalItemPO> abnormalItemPOList = abnormalItemPOMapper.selectList(wrapper);
        if (CollUtil.isEmpty(abnormalItemPOList)) return null;
        // 3.获取所有可用的异常处理列表
        LambdaQueryWrapper<AbHandleItemPO> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(AbHandleItemPO::getSecDeptID, secDeptIDList)
                .eq(AbHandleItemPO::getEnabled, true);
        List<AbHandleItemPO> abHandleItemPOList = abHandleItemPOMapper.selectList(wrapper1);

        // 4. 组装view层数据
        List<AbnormalItemDTO> abnormalItemDTOList = CollUtil.list(false);
        CollUtil.forEach(abnormalItemPOList.iterator(), (abnormalItemPO, index) -> {
            AbnormalItemDTO abnormalItemDTO = new AbnormalItemDTO();
            abnormalItemDTO.setAbnormalItem(abnormalItemPO);
            abnormalItemDTO.setSecDept(
                    CollUtil.findOne(secDeptList, secDept -> {
                        return secDept.getDepartmentID().equals(abnormalItemPO.getSecDeptID());
                    })
            );
            if (StrUtil.isNotEmpty(abnormalItemPO.getBelong2MacNo())) {
                abnormalItemDTO.setMachine(
                        CollUtil.findOne(machineDTOList, machineDTO -> {
                            return machineDTO.getMachine().getMachineNo().equals(abnormalItemPO.getBelong2MacNo());
                        })
                );
            }
            if (StrUtil.isNotEmpty(abnormalItemPO.getAbHandleList())) {
                List<String> abHandleIDList = StrUtil.split(abnormalItemPO.getAbHandleList().replaceAll("[;；，,]", ";"), ";");
                //List<String> abHandleIDList = StrUtil.split(StrUtil.replace(abnormalItemPO.getAbHandleList(), "；", ";"), ";");
                List<AbHandleItemPO> tmpAbHanleItemList = CollUtil.list(false);
                CollUtil.forEach(abHandleIDList.iterator(), (abHandleID, idx) -> {
                    tmpAbHanleItemList.add(
                            CollUtil.findOne(abHandleItemPOList, abHandleItemPO -> {
                                return abHandleItemPO.getAbHandleItemID().equals(Integer.parseInt(abHandleID));
                            })
                    );
                });
                abnormalItemDTO.setAbHandleList(tmpAbHanleItemList);
            }
            abnormalItemDTOList.add(abnormalItemDTO);
        });
        // 5. 过滤数据
        CollUtil.removeNull(abnormalItemDTOList);
        CollUtil.filter(abnormalItemDTOList, abnormalItemDTO -> {
            return (ObjectUtil.isNotEmpty(abnormalItemDTO.getSecDept()));
        });
        //6. 搜索过滤
        CollUtil.filter(abnormalItemDTOList, abnormalItemDTO -> {
            return abnormalItemDTO.getAbnormalItem().getAbnormalItemName().contains(keyword);
        });

        return abnormalItemDTOList;
    }

    @Override
    public int uptAbnormalItemEnabled(Integer abnormalItemID, Boolean enabled) {
        AbnormalItemPO abnormalItemPO = new AbnormalItemPO();
        abnormalItemPO.setAbnormalItemID(abnormalItemID);
        abnormalItemPO.setEnabled(enabled);
        return abnormalItemPOMapper.updateById(abnormalItemPO);
    }

    @Override
    public int delAbnormalItem(Integer abnormalItemID) {
        return abnormalItemPOMapper.deleteById(abnormalItemID);
    }

    @Override
    public int addAbnormalItem(AbnormalItemPO abnormalItemPO) {
        abnormalItemPO.setAbnormalItemContent(Convert.toDBC(abnormalItemPO.getAbnormalItemContent()));
        abnormalItemPO.setAbHandleList(Convert.toDBC(abnormalItemPO.getAbHandleList()));
        return abnormalItemPOMapper.insert(abnormalItemPO);
    }

    @Override
    public int uptAbnormalItem(AbnormalItemPO abnormalItemPO) {
        abnormalItemPO.setAbnormalItemContent(Convert.toDBC(abnormalItemPO.getAbnormalItemContent()));
        abnormalItemPO.setAbHandleList(Convert.toDBC(abnormalItemPO.getAbHandleList()));
        return abnormalItemPOMapper.updateById(abnormalItemPO);
    }

    @Override
    public List<AbnormalItemDTO> getAbnormalItemListByMachineNo(String machineNo) {
        //1.通过设备获取secDeptID
        MachinePO machinePO = machineService.get1ByMachineNo_Usable(machineNo);
        if (ObjectUtil.isEmpty(machinePO)) return null;
        //2. 获取数据
        LambdaQueryWrapper<AbnormalItemPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AbnormalItemPO::getEnabled, true)
            .and(i->{
                i.eq(AbnormalItemPO::getSecDeptID,machinePO.getSecDeptID())
                .or()
                .eq(AbnormalItemPO::getBelong2MacNo,machinePO.getMachineNo());
            });
        List<AbnormalItemPO> abnormalItemPOList = abnormalItemPOMapper.selectList(wrapper);
        // 3.获取所有可用的异常处理列表
        LambdaQueryWrapper<AbHandleItemPO> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(AbHandleItemPO::getSecDeptID, machinePO.getSecDeptID())
                .eq(AbHandleItemPO::getEnabled, true);
        List<AbHandleItemPO> abHandleItemPOList = abHandleItemPOMapper.selectList(wrapper1);
        // 4.组装view层数据
        List<AbnormalItemDTO> abnormalItemDTOList = CollUtil.list(false);
        CollUtil.forEach(abnormalItemPOList.iterator(),(abnormalItemPO, index) -> {
            AbnormalItemDTO abnormalItemDTO = new AbnormalItemDTO();
            abnormalItemDTO.setAbnormalItem(abnormalItemPO);
            if(StrUtil.isNotEmpty(abnormalItemPO.getAbHandleList())){
                List<String> abHandleIDList = StrUtil.split(abnormalItemPO.getAbHandleList().replaceAll("[;；，,]", ";"), ";");
                List<AbHandleItemPO> tmpAbHanleItemList = CollUtil.list(false);
                CollUtil.forEach(abHandleIDList.iterator(), (abHandleID, idx) -> {
                    tmpAbHanleItemList.add(
                            CollUtil.findOne(abHandleItemPOList, abHandleItemPO -> {
                                return abHandleItemPO.getAbHandleItemID().equals(Integer.parseInt(abHandleID));
                            })
                    );
                });
                abnormalItemDTO.setAbHandleList(tmpAbHanleItemList);
            }
            abnormalItemDTOList.add(abnormalItemDTO);
        });
        // 5. 过滤数据
        CollUtil.removeNull(abnormalItemDTOList);

        return abnormalItemDTOList;
    }

    @Override
    public AbnormalItemDTO getAbnormalItemByOpItemNameAndMachineNo(String opItemName, String machineNo) {
        //1.通过设备获取secDeptID
        MachinePO machinePO = machineService.get1ByMachineNo_Usable(machineNo);
        if (ObjectUtil.isEmpty(machinePO)) return null;
        //2. 获取数据
        LambdaQueryWrapper<AbnormalItemPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AbnormalItemPO::getAbnormalItemName,opItemName)
                .and(i->{
                    i.eq(AbnormalItemPO::getSecDeptID,machinePO.getSecDeptID())
                            .or()
                            .eq(AbnormalItemPO::getBelong2MacNo,machinePO.getMachineNo());
                })
                .last("LIMIT 1");
        AbnormalItemPO abnormalItemPO = abnormalItemPOMapper.selectOne(wrapper);
        // 3.获取所有可用的异常处理列表
        LambdaQueryWrapper<AbHandleItemPO> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(AbHandleItemPO::getSecDeptID, machinePO.getSecDeptID())
                .eq(AbHandleItemPO::getEnabled, true);
        List<AbHandleItemPO> abHandleItemPOList = abHandleItemPOMapper.selectList(wrapper1);
        // 4.组装view数据
        AbnormalItemDTO abnormalItemDTO = new AbnormalItemDTO();
        abnormalItemDTO.setAbnormalItem(abnormalItemPO);
        abnormalItemDTO.setAbHandleList(abHandleItemPOList);


        return abnormalItemDTO;
    }
}
